package com.atguigu.stack;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class PolandNotation {
    public static void main(String[] args) {
        // 后缀表达式（逆波兰表达式），用空格分开为了方便
        String suffixExpression = "4 5 * 8 - 60 + 8 2 / +";// 4*5-8+60+8/2=76
        List<String> rpnList = getListString(suffixExpression);
        int res = parseSuffixExpressionList(rpnList);
        System.out.println(res);
    }

    public static List<String> getListString(String suffixExpression) {
        String[] split = suffixExpression.split(" ");
        List<String> list = new ArrayList<>();
        for (String ele : split) {
            list.add(ele);
        }
        return list;
    }

    public static int parseSuffixExpressionList(List<String> ls) {
        Stack<String> s1 = new Stack<String>();
        for (String item : ls) {
            if (item.matches("\\d+")) {//todo 正则表达式
                //如果是数字，入栈
                s1.push(item);
            } else {
                int num2 = Integer.parseInt(s1.pop());
                int num1 = Integer.parseInt(s1.pop());
                int res = 0;
                if ("+".equals(item)) {
                    res = num1 + num2;
                } else if ("-".equals(item)) {
                    res = num1 - num2;
                } else if ("*".equals(item)) {
                    res = num1 * num2;
                } else if ("/".equals(item)) {
                    res = num1 / num2;
                } else {
                    throw new RuntimeException("无效符号");
                }
                s1.push(res + "");
            }
        }
        return Integer.parseInt(s1.pop());
    }
}
